import React, { useState, useEffect } from 'react'
import { Table, Button, Space, Modal, Form, Input, Tag, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'

function Members() {
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [editingMember, setEditingMember] = useState(null)
    const [form] = Form.useForm()
    const [members, setMembers] = useState([
        {
            id: '001',
            name: '张三',
            phone: '13800138000',
            level: 'VIP',
            points: 1000,
        },
        {
            id: '002',
            name: '李四',
            phone: '13900139000',
            level: '普通',
            points: 500,
        }
    ])

    useEffect(() => {
        if (!isModalVisible) {
            form.resetFields()
        }
    }, [isModalVisible, form])

    const handleEdit = (record) => {
        console.log(record)
        setEditingMember(record)
        setTimeout(() => {
            form.setFieldsValue(record)
        }, 0)
        showModal()
    }

    const handleDelete = (record) => {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除会员 ${record.name} 吗？`,
            onOk() {
                setMembers(members.filter(item => item.id !== record.id))
                message.success('删除成功')
            }
        })
    }

    const showModal = () => {
        setIsModalVisible(true)
        if (!editingMember) {
            form.resetFields()
        }
    }

    const handleCancel = () => {
        setTimeout(() => {
            setIsModalVisible(false)
            setEditingMember(null)
            form.resetFields()
        }, 200)
    }

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields()
            console.log(values)
            if (editingMember) {
                setMembers(members.map(item =>
                    item.id === editingMember.id
                        ? { ...item, ...values }
                        : item
                ))
                message.success('编辑成功')
            } else {
                const newMember = {
                    id: `00${members.length + 1}`,
                    ...values,
                    level: '普通',
                    points: 0
                }
                setMembers([...members, newMember])
                message.success('添加成功')
            }
            handleCancel()
        } catch (error) {
            console.error('Validate Failed:', error)
            const errorFields = error.errorFields
            if (errorFields && errorFields.length > 0) {
                message.error(errorFields[0].errors[0])
            }
        }
    }

    const columns = [
        {
            title: '会员编号',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '会员等级',
            dataIndex: 'level',
            key: 'level',
            render: (level) => (
                <Tag color={level === 'VIP' ? 'gold' : 'green'}>
                    {level}
                </Tag>
            ),
        },
        {
            title: '积分',
            dataIndex: 'points',
            key: 'points',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button type="link" onClick={() => handleEdit(record)}>
                        编辑
                    </Button>
                    <Button type="link" danger onClick={() => handleDelete(record)}>
                        删除
                    </Button>
                </Space>
            ),
        },
    ]

    return (
        <div>
            <div style={{ marginBottom: 16 }}>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={showModal}
                >
                    新增会员
                </Button>
            </div>

            <Table
                columns={columns}
                dataSource={members}
                rowKey="id"
                pagination={{
                    pageSize: 10,
                    showTotal: (total) => `共 ${total} 条记录`
                }}
            />

            <Modal
                title={editingMember ? '编辑会员' : '新增会员'}
                open={isModalVisible}
                onOk={handleSubmit}
                onCancel={handleCancel}
                maskClosable={false}
                destroyOnClose={false}
                className="custom-modal"
                transitionName=""
                maskTransitionName=""
                wrapClassName={isModalVisible ? 'ant-modal-wrap' : ''}
                modalRender={(modal) => (
                    <div onClick={(e) => e.stopPropagation()}>
                        {modal}
                    </div>
                )}
                footer={[
                    <Button
                        key="cancel"
                        onClick={handleCancel}
                        className="modal-btn"
                    >
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        onClick={handleSubmit}
                        className="modal-btn btn-shine"
                    >
                        确定
                    </Button>
                ]}
            >
                <Form
                    form={form}
                    layout="vertical"
                    preserve={false}
                    className="custom-form"
                >
                    <Form.Item
                        name="name"
                        label="姓名"
                        rules={[{ required: true, message: '请输入姓名' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="phone"
                        label="手机号"
                        rules={[
                            { required: true, message: '请输入手机号' },
                            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                        ]}
                    >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default Members 